<template>
  <div class="applications-container">
    <div class="page-header">
      <h1 class="page-title">申请记录管理</h1>
      <p class="page-subtitle">管理收到的岗位申请，及时处理人才对接</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon pending">
          <el-icon size="24"><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.pending }}</div>
          <div class="stat-label">待处理</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon approved">
          <el-icon size="24"><Check /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.approved }}</div>
          <div class="stat-label">已通过</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon rejected">
          <el-icon size="24"><Close /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.rejected }}</div>
          <div class="stat-label">已拒绝</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon total">
          <el-icon size="24"><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.total }}</div>
          <div class="stat-label">总申请</div>
        </div>
      </div>
    </div>

    <!-- 申请列表 -->
    <el-card class="applications-card">
      <template #header>
        <div class="card-header">
          <h3>申请列表</h3>
          <div class="header-actions">
            <el-button @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>

          </div>
        </div>
      </template>

      <el-table 
        :data="applications" 
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="applicantName" label="申请人" width="120">
          <template #default="scope">
            <div class="applicant-info">
              <div class="applicant-name">{{ scope.row.applicantName }}</div>
              <div class="applicant-email">{{ scope.row.applicantEmail }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="positionName" label="申请岗位" width="150" />
        
        <el-table-column prop="applyTime" label="申请时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.applyTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="education" label="学历" width="100" />
        
        <el-table-column prop="experience" label="经验" width="100" />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                size="small" 
                type="primary" 
                @click="viewDetail(scope.row)"
              >
                查看详情
              </el-button>
              
              <el-button 
                v-if="scope.row.status === 'pending'"
                size="small" 
                type="success" 
                @click="handleApprove(scope.row)"
              >
                通过
              </el-button>
              
              <el-button 
                v-if="scope.row.status === 'pending'"
                size="small" 
                type="danger" 
                @click="handleReject(scope.row)"
              >
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Clock, Check, Close, Document, Refresh
} from '@element-plus/icons-vue'
import { enterpriseApi } from '@/api'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const applications = ref([])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 统计数据
const stats = reactive({
  pending: 0,
  approved: 0,
  rejected: 0,
  total: 0
})

// 加载申请列表数据
const loadApplications = async () => {
  loading.value = true
  try {
    const response = await enterpriseApi.getApplications({
      page: currentPage.value,
      size: pageSize.value
    })
    
    if (response.code === 200) {
      // 处理返回的数据结构
      const data = response.data
      if (data && data.requests) {
        applications.value = data.requests.map((request) => {
          return {
            id: request.id || request.requestId || request.application_id,
            applicantName: request.studentName || request.applicantName || request.student_name || '未知',
            applicantEmail: request.studentEmail || request.applicantEmail || request.student_email || '',
            positionName: request.demandTitle || request.positionName || request.demand_title || '未知岗位',
            status: request.status || request.application_status || 'pending',
            applyTime: request.createTime || request.applyTime || request.application_time || '',
            education: request.education || request.education_requirement || '未知',
            experience: request.experience || request.experience_requirement || '未知',
            // 保留原始数据
            originalData: request
          }
        })
        
        // 更新统计数据
        updateStats()
        ElMessage.success(`申请列表加载成功，共 ${applications.value.length} 条记录`)
      } else {
        applications.value = []
        ElMessage.info('暂无申请记录')
      }
    } else {
      ElMessage.error(response.message || '获取申请列表失败')
    }
  } catch (error) {
    console.error('加载申请列表失败:', error)
    ElMessage.error('获取申请列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStats = () => {
  const allApplications = applications.value
  stats.pending = allApplications.filter(app => app.status === 'pending').length
  stats.approved = allApplications.filter(app => app.status === 'approved').length
  stats.rejected = allApplications.filter(app => app.status === 'rejected').length
  stats.total = allApplications.length
}

// 刷新数据
const refreshData = async () => {
  await loadApplications()
}

// 查看详情
const viewDetail = (row) => {
  ElMessage.info(`查看 ${row.applicantName} 的申请详情`)
}

// 通过申请
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要通过这个申请吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API处理申请
    const response = await enterpriseApi.handleApplication(row.id, 'approve')
    
    if (response.code === 200) {
      ElMessage.success(`${row.applicantName} 的申请已通过`)
      row.status = 'approved'
      updateStats()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('通过申请失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 拒绝申请
const handleReject = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要拒绝这个申请吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API处理申请
    const response = await enterpriseApi.handleApplication(row.id, 'reject')
    
    if (response.code === 200) {
      ElMessage.success(`${row.applicantName} 的申请已拒绝`)
      row.status = 'rejected'
      updateStats()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒绝申请失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 工具函数
const getStatusType = (status) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'approved': return 'success'
    case 'rejected': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'pending': return '待处理'
    case 'approved': return '已通过'
    case 'rejected': return '已拒绝'
    default: return '未知'
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}



// 生命周期
onMounted(() => {
  // 组件挂载时加载数据
  loadApplications()
})
</script>

<style scoped>
/* 页面内容样式 */
.applications-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: left;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.pending {
  background: linear-gradient(135deg, #E6A23C, #F7BA2A);
}

.stat-icon.approved {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stat-icon.rejected {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.stat-icon.total {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 申请列表卡片 */
.applications-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 表格样式 */
.applicant-info {
  display: flex;
  flex-direction: column;
}

.applicant-name {
  font-weight: 500;
  color: #303133;
}

.applicant-email {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}
</style> 